﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic.CompilerServices;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace TianYu.CMS.WebApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UploadFileController : ControllerBase
    {
        private readonly ILogger<WeatherForecastController> _logger;
        public IWebHostEnvironment _webHostEnvironment;

        public UploadFileController(ILogger<WeatherForecastController> logger, IWebHostEnvironment webHostEnvironment)
        {
            _logger = logger;
            this._webHostEnvironment = webHostEnvironment;
        }

        [HttpGet]
        public async Task<string> Upload()
        {
            var files = Request.Form.Files;

            if (files.Count < 1)
            {
                return "没有选择上传文件";
            }
            var rootPath = _webHostEnvironment.WebRootPath;

            var formFile = files[0];
            //文件后缀
            var fileExtension = Path.GetExtension(formFile.FileName).ToLower();

            string newFileName = DateTime.Now.ToString("ssss") + fileExtension;
            string saveDir = DateTime.Now.ToString("yyyyMM");
            string savePath = Path.Combine(rootPath, "UploadFile", saveDir);

            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            using (var stream = System.IO.File.Create(Path.Combine(savePath, newFileName)))
            {
                await formFile.CopyToAsync(stream); 
            }
            return savePath;
        }
    }
}
